<!DOCTYPE html>
<!-- rcastaneda -->

<html lang="en">
    <head>
        <title>EAX - Tweaks</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
        <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

        <script type="text/javascript" src="http://api.bridgeit.mobi/bridgeit/bridgeit.js"></script>

        <style>
            .body{
                background-image: url("src/img/pw_maze_black_@2X.png"); 
                background-repeat: repeat;
            }
        </style>

        <script type="text/javascript">
var uploadServiceURL = 'http://api.bridgeit.mobi/echo/';
function onAfterPhotoCapture(event) {
    var cameraBtn = document.getElementById('cameraBtn');
    if (event.preview) {
        //show the thumbnail preview
        var thumbnailElem = document.createElement("img");
        thumbnailElem.setAttribute('src', event.preview);
        thumbnailElem.style.float = 'right';
    }
    if (event.response) {
        //show the image
        var photoURL = event.response;
        var imageLink = document.createElement('a');
        imageLink.setAttribute('class', 'button');
        imageLink.innerHTML = 'Click to view the photo';
        imageLink.setAttribute('href', photoURL);
        //set the thumbnail img as the link child
        imageLink.appendChild(thumbnailElem);
        //append the new link after the camera btn
        cameraBtn.parentNode.appendChild(imageLink);
    }
}


        </script>


<script type="text/javascript">
                        window.geoTracking = false;

                        var geoPushReady;

                        function isGeoTrackRunning() {
                            var result = false;
                            if (window.localStorage && localStorage.getItem('bridgeit.geoTrackRunning') === 'true') {
                                result = true;
                            }
                            return result;
                        }

                        function setGeoTrackRunning(running) {
                            if (window.localStorage) {
                                localStorage.setItem('bridgeit.geoTrackRunning', running);
                            }
                            refreshGeoTrackButtons(running);
                        }

                        function refreshGeoTrackButtons(running) {
                            document.getElementById('startTrackingBtn').style.display = running ? 'none' : '';
                            document.getElementById('stopTrackingBtn').style.display = running ? '' : 'none';
                        }

                        refreshGeoTrackButtons(isGeoTrackRunning());

                        if (!geoPushReady) {
                            bridgeit.usePushService(window.pushHub, window.apiKey);
                            bridgeit.addPushListener("geotrack-" + bridgeit.getId(),
                                    "onReceiveGeoTrackPush");
                            geoPushReady = true;
                        }

                        function onReceiveGeoTrackPush() {
                            console.log("geotrack Push received");
                            updateMarkers();
                        }

                        function addLocationUpdateRow(geojson) {
                            if (geojson) {
                                var updatesTbl = document.getElementById('geoTrackPushUpdatesTbl');
                                var updateRow = updatesTbl.insertRow(0);

                                var timeCell = updateRow.insertCell(0);
                                var timeProp = getTimestampFromGeoJson(geojson);
                                if (timeProp) {
                                    var time = new Date(timeProp);
                                    var timeString = dateTimeStringFromDate(time);
                                    timeCell.innerHTML = '<span>' + timeString + '</span>';
                                    updateRow.style.backgroundColor = colorFromTimestamp(timeProp);

                                }

                                var latCell = updateRow.insertCell(1);
                                var lat = geojson.geometry.coordinates[1];
                                latCell.innerHTML = '<span>' + lat.toFixed(4) + '</span>';

                                var lngCell = updateRow.insertCell(2);
                                var lng = geojson.geometry.coordinates[0];
                                lngCell.innerHTML = '<span>' + lng.toFixed(4) + '</span>';

                                var accuracyCell = updateRow.insertCell(3);
                                if (geojson.properties.accuracy) {
                                    accuracyCell.innerHTML = '<span>' + geojson.properties.accuracy.toFixed(0) + 'm</span>';
                                } else {
                                    accuracyCell.innerHTML = '<span></span>';
                                }

                                updateRow.addEventListener('click', function() {
                                    moveCursorMarker(lat, lng);
                                    var prev = document.querySelector('.geotrack-updates .active');
                                    if (prev) {
                                        prev.classList.remove('active');
                                    }
                                    this.classList.add('active');
                                }, false);
                            }
                        }

                        function onAfterTrackingStarted() {
                            console.log('geoTrack onAfterTrackingStarted');
                            setGeoTrackRunning(true);
                        }

                        function onAfterTrackingStopped() {
                            console.log('geoTrack onAfterTrackingStopped');
                            setGeoTrackRunning(false);
                        }

                        function geoTrackVisible() {
                            initTrackMap();
                            setTimeout(function() {
                                google.maps.event.trigger(geoTrackMap, 'resize');
                                updateMarkers();
                            }, 1000);
                        }

                        var geoTrackMap;
                        var geoTrackMapMarkers = [];

                        function initTrackMap() {
                            console.log('geoTrack initTrackMap');
                            if (!window.geoTracking) {
                                window.geoTracking = true;
                                var mapOptions = {
                                    center: new google.maps.LatLng(-34.397, 150.644),
                                    maxZoom: 20,
                                    zoom: 8,
                                    draggable: false,
                                    mapTypeId: google.maps.MapTypeId.ROADMAP
                                };
                                geoTrackMap = new google.maps.Map(document
                                        .getElementById('trackMapCanvas'), mapOptions);
                                var overlay = document.getElementById('trackMapOverlay');
                                geoTrackMap.controls[google.maps.ControlPosition.RIGHT_TOP]
                                        .push(overlay);
                            }
                        }

                        function updateMarkers() {
                            console.log('geoTrack updateMarkers');
                            ajaxGet(window.echoHub + 'list/geotrack-' + bridgeit.getId(), processMarkers);
                        }

                        function getTimestampFromGeoJson(geojson) {
                            var timeProp;
                            if (geojson.properties && geojson.properties.time) {
                                timeProp = geojson.properties.time;
                            }
                            else if (geojson.properties && geojson.properties.timestamp) {
                                timeProp = geojson.properties.timestamp;
                            }
                            return timeProp;
                        }

                        function colorFromTimestamp(time) {
                            var hexString = time.toString(16).slice(-6);
                            var rgb = [];
                            //allow only lighter colors for readability
                            rgb[0] = parseInt("0x" + hexString.slice(-6, -4));
                            rgb[1] = parseInt("0x" + hexString.slice(-4, -2));
                            rgb[2] = parseInt("0x" + hexString.slice(-2));

                            for (var i = 0; i < 3; i++) {
                                if (rgb[i] < 128) {
                                    rgb[i] += 128;
                                    rgb[i] = ('00' + rgb[i].toString(16)).slice(-2);
                                }
                            }
                            var color = '#';
                            for (var i = 0; i < 3; i++) {
                                color += ('00' + rgb[i].toString(16)).slice(-2);
                            }
                            return color;
                        }

                        function randomColor() {
                            var letters = '0123456789ABCDEF'.split('');
                            var color = '#';
                            for (var i = 0; i < 6; i++) {
                                color += letters[Math.round(Math.random() * 15)];
                            }
                            return color;
                        }
                        var cursorMarker = new google.maps.Marker({
                            position: new google.maps.LatLng(0, 0),
                            icon: {
                                path: google.maps.SymbolPath.CIRCLE,
                                strokeColor: '#FF0000',
                                scale: 5
                            }
                        });

                        function moveCursorMarker(lat, lng) {
                            cursorMarker.setPosition(new google.maps.LatLng(lat, lng));
                            cursorMarker.setMap(geoTrackMap);
                            console.log('moved cursorMarker to ' + lat + ',' + lng);
                        }

                        function processMarkers(data) {
                            console.log('geoTrack processMarkers: data=' + data);
                            if (data) {
                                var markerData = JSON.parse(data);
                                var len = markerData.length;
                                var markersPlaced = false;
                                var locations = {};
                                var locationKeys = [];
                                var markerIdx = -1;
                                var markerIdxLgth = len;
                                for (var i = 0; i < len; i++) {

                                    //google maps follows english usage LatLang
                                    //rather than standard x,y coordinate longitude,latitude
                                    var coordinates = markerData[i].geometry.coordinates;
                                    var location = new google.maps.LatLng(
                                            coordinates[1], coordinates[0]);
                                    var locationKey = markerData[i].properties.jguid;
                                    if (!locationKey) {
                                        locationKey = '999999'; //when no jguid available just use medium gray
                                    }
                                    if (locationKeys.indexOf(locationKey) < 0) {
                                        locationKeys.push(locationKey);
                                        locations[locationKey] = [];
                                    }
                                    var ts = getTimestampFromGeoJson(markerData[i]);

                                    //check if provided marker is too close to existing marker
                                    var existLen = geoTrackMapMarkers.length;
                                    var minDistance = 100;
                                    for (var j = 0; j < existLen; j++) {
                                        var distance = google.maps.geometry.spherical
                                                .computeDistanceBetween(location,
                                                        geoTrackMapMarkers[j].position);
                                        if (distance < minDistance) {
                                            minDistance = distance;
                                        }
                                    }
                                    if (minDistance < 5) {
                                        markerIdxLgth--;
                                        continue;
                                    }
                                    markerIdx++;
                                    locations[locationKey].push(location);
                                    addLocationUpdateRow(markerData[i]);

                                    markersPlaced = true;
                                    var markerColor = colorFromTimestamp(ts);
                                    /*
                                     if( markerIdx == 0 ){
                                     markerColor = '#00FF00';
                                     }
                                     else if( markerIdx == markerIdxLgth-1){
                                     markerColor = '#FF0000';
                                     }*/
                                    var marker = new google.maps.Marker({
                                        position: location,
                                        icon: {
                                            path: google.maps.SymbolPath.CIRCLE,
                                            strokeColor: markerColor,
                                            scale: 4
                                        },
                                        map: geoTrackMap
                                    });
                                    geoTrackMapMarkers.push(marker);

                                    document.getElementById("trackMapDetail").innerHTML =
                                            coordinates[0].toFixed(2) + "," +
                                            coordinates[1].toFixed(2) + " " +
                                            (coordinates[2] ? (coordinates[2].toFixed(2) + "m  ") : "");
                                }

                                if (markersPlaced) {
                                    var existLen = geoTrackMapMarkers.length;
                                    var bounds = new google.maps.LatLngBounds();
                                    for (var j = 0; j < existLen; j++) {
                                        bounds.extend(geoTrackMapMarkers[j].position);
                                    }
                                    geoTrackMap.fitBounds(bounds);
                                    //zoom out a bit if only one marker
                                    if (existLen === 1) {
                                        geoTrackMap.setZoom(10);
                                    }
                                    for (var k = 0; k < locationKeys.length; k++) {
                                        var markerColor = "#" + locationKeys[k].substring(0, 6);
                                        var path = new google.maps.Polyline({
                                            path: locations[locationKeys[k]],
                                            geodesic: true,
                                            strokeColor: markerColor,
                                            strokeOpacity: 0.5,
                                            strokeWeight: 1
                                        });
                                        path.setMap(geoTrackMap);

                                    }

                                }

                            }
                            else {
                                console.log('no data for geotrack...')
                            }
                        }

                    </script>

    </head>

    <body>
        <div data-role="page" data-theme="c"  class="body" id="body"  >

            <div data-role="header" data-theme="b">
                <a href="#" data-role="button" data-icon="grid">Home</a>
                <h1> Who the fuck cares about? </h1>
            </div>

            <div data-role="content">

                <button id='cameraBtn'  type="button"
                        onclick="bridgeit.camera('cameraBtn', 'onAfterPhotoCapture', {postURL: uploadServiceURL + 'camera-upload/'});">
                    Take a Photo</button>


                <button onclick="bridgeit.geoTrack('tracker', 'handleTrack',
                                {postURL: 'http://api.bridgeit.mobi/echo/service/echoput/geotrack-tutorial'});">Track</button>


                <div id="geotrack" title="Locate It" class="panel" onfocus="geoTrackVisible();">
                    <script>
                        $(document).on("pageshow", "#geotrack", function() {
                            geoTrackVisible();
                        });
                    </script>
                    <h2>GeoTrack Location Tracking</h2>
                    <fieldset class="desc">
                        <div class="row">
                          
                        </div>
                                            </fieldset>

                    <button id="startTrackingBtn" type="button" class="btn" style="display: none"
                            onclick="bridgeit.geoTrack('tracker', 'onAfterTrackingStarted', {postURL: window.echoHub + 'list/geotrack-' + bridgeit.getId(), strategy: 'significant', duration: 0.3, _jguid: bridgeit.getId()});">Start Tracking</button>
                    <button id="stopTrackingBtn" type="button" class="btn" style="display: none"
                            onclick="bridgeit.geoTrack('tracker', 'onAfterTrackingStopped', {postURL: window.echoHub + 'list/geotrack-' + bridgeit.getId(), strategy: 'stop', _jguid: bridgeit.getId()});">
                        Stop Tracking
                        <i class="icon-gear icon-spin geotracking"></i>
                    </button>

                    <h4>Location Updates</h4>
                    <div id="geoTrackPushUpdates" class="geotrack-updates">
                        <table id="geoTrackPushUpdatesHdr" class="hdr">
                            <thead>
                            <th>Time</th><th>Latitude</th><th>Longitude</th><th>Accuracy</th>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                        <div class="data">
                            <table id="geoTrackPushUpdatesTbl">
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="trackMapCanvas" style="height:200px"></div>
                    <div id="trackMapOverlay" >
                        <span id="trackMapDetail" style="background-color:white"></span>
                    </div>
                    
                </div>


            </div>


        </div>
    </body>

</html>
